import openai
import os

f = open("api.txt")  #  提前将api key保存在api.txt中
openai.api_key = f.read()

os.environ["http_proxy"] = "http://127.0.0.1:7890"
os.environ["https_proxy"] = "http://127.0.0.1:7890"


def generate_answer(messages):
    try:
        response = openai.ChatCompletion.create(
              model="gpt-3.5-turbo",
              messages=messages,
              stream=True,
              temperature=0.2
        )
        collected_messages = []
        for chunk in response:
            chunk_message = chunk['choices'][0]['delta']
            print(chunk_message.get('content', ''), end='')
            collected_messages.append(chunk_message)
        full_reply_content = ''.join([m.get('content', '') for m in collected_messages])
        return full_reply_content

    except Exception as e:
        print("错误: ", e)
        return ""


def add_to_list(lst, new_item):
    if len(lst) < 9:
        lst.append(new_item)
    else:
        lst.pop(7)
        lst.pop(7)
        lst.append(new_item)


if __name__ == '__main__':
    # 进行对话
    message_dic = [
        {"role": "system", "content": "我提供单词，你按照特定格式返回该单词的词性、音标、2个相同意思的描述、3个简单的例子。"},
        {"role": "user", "content":"assumption"},
        {"role": "assistant", "content":"#assumption(n)\n#d assumption音标\n/əˈsʌmpʃn/\n#d assumption描述1\nsomething that you accept as true without question or proof\n#d assumption描述2\nIf you make an assumption that something is true or will happen, you accept that it is true or will happen, often without any real proof.\n#e assumption例子1\nThey make the naive assumption that because it's popular it must be good.\n#e assumption例子2\nLots of evidence supports this assumption.\n#e assumption例子3\nI really don't like you making assumptions about what I think."},
        {"role": "user", "content":"incorporate"},
        {"role": "assistant", "content":"#incorporate(v)\n#d incorporate音标\n/ɪnˈkɔːpəreɪt/\n#d incorporate描述1\nto include something as part of something larger\n#d incorporate描述2\nIf one thing incorporates another thing, it includes the other thing.\n#e incorporate例子1\nMany of your suggestions have been incorporated in the plan.\n#e incorporate例子2\nThe new car design incorporates all the latest safety features.\n#e incorporate例子3\nThis design incorporates the best features of our earlier models."},
        {"role": "user", "content":"comprehensive"},
        {"role": "assistant", "content": "#comprehensive(adj)\n#d comprehensive音标\n/ˌkɒm.prɪˈhen.sɪv/\n#d comprehensive描述1\ncomplete and including everything that is necessary.\n#d comprehensive描述2\nincluding all, or almost all, the items, details, facts, information, etc., that may be involved\n#e comprehensive例子1\nIs this list comprehensive or are there some names missing?\n#e comprehensive例子2\nHe has written a fully comprehensive guide to Rome.\n#e comprehensive例子3\nIf you are a young, inexperienced driver, it is worth having comprehensive insurance."}
    ]
    while True:
        user_input = input("user: ")
        if user_input.lower() == 'quit':
            break
        user_input_dic = {"role": "user", "content": user_input}
        add_to_list(message_dic, user_input_dic)
        # print("assistant: ", end='')
        assistant_output = generate_answer(message_dic)
        print()
        assistant_output_dic = {"role": "assistant", "content": assistant_output}
        with open("word.txt", "a", encoding='utf-8') as file:
            file.write("\n" + assistant_output)
        add_to_list(message_dic, assistant_output_dic)
            